package com.liuqi.knet.remoting.exchange;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

/**
 * 数据传输 - 事件, 事件类型有(心跳/鉴权/连接状态)等
 *
 * @see Type
 *
 * @author liuqi
 * @date 2024/12/17 15:17
 **/
@Getter
@Setter
@ToString
public class Event {

    /**
     * 消息ID,
     *
     * Event通信一般是不需要ID的, 此ID是为了客户端再发送请求后, 服务端响应错误事件时, 和客户端请求进行匹配
     */
    private long id;

    /**
     * 事件类型
     */
    private Type type;

    /**
     * 事件消息
     */
    private Object data;

    public Event() {
    }

    public Event(Type type) {
        this.type = type;
    }

    public Event(long id, Type type) {
        this.id = id;
        this.type = type;
    }

    public Event(Type type, Object data) {
        this.type = type;
        this.data = data;
    }

    public Event(long id, Type type, Object data) {
        this.id = id;
        this.type = type;
        this.data = data;
    }

    public void setType(byte value) {
        switch (value) {
            case 1:
                this.type = Type.CONNECT_OK;
                break;
            case 2:
                this.type = Type.CONNECT_FAIL;
                break;
            case 3:
                this.type = Type.BIND_OK;
                break;
            case 4:
                this.type = Type.BIND_FAIL;
                break;
            case 5:
                this.type = Type.HEARTBEAT;
                break;
            case 6:
                this.type = Type.REJECT_CONNECTION;
                break;
            default:
                throw new IllegalArgumentException("无效的Event.Type.value: " + value + ". Event.Types: " + Type.print());
        }
    }

    /**
     * 事件类型
     *
     */
    public enum Type {
        /**
         * 客户端建立连接成功
         */
        CONNECT_OK((byte) 1),

        /**
         * 客户端建立连接失败
         */
        CONNECT_FAIL((byte) 2),

        /**
         * 服务端绑定成功
         */
        BIND_OK((byte) 3),

        /**
         * 服务端绑定失败
         */
        BIND_FAIL((byte) 4),

        /**
         * 由客户端发起, 心跳
         */
        HEARTBEAT((byte) 5),

        /**
         * 拒绝连接
         */
        REJECT_CONNECTION((byte) 6),
        ;

        byte value;

        Type(byte value) {
            this.value = value;
        }

        public byte value() {
            return value;
        }

        public static String print() {
            Type[] values = Type.values();
            StringBuilder buf = new StringBuilder();
            for (Type type : values) {
                buf.append("{name: ")
                        .append(type.name())
                        .append(", value: ")
                        .append(type.value())
                        .append("}, ");
            }

            return buf.toString();
        }

    }

}
